const fs = require("fs")

exports.add = function (student, callBack) {
    readStudentList(function (json) {
        json.primaryKey = ++json.primaryKey
        student.id = json.primaryKey;
        json.studentList.push(student)
        writeStudentList(json)
        callBack()
    })
}


exports.getById = function (id, callBack) {
    readStudentList(function (json) {
        let editStudent = json.studentList.find(i => i.id === id)
        callBack(editStudent)
    })
}


exports.update = function (editStudent, callBack) {
    readStudentList(function (json) {
        let stu = json.studentList.find(i => i.id == editStudent.id)

        //用传进来的对象的可枚举属性做循环
        for (let key in editStudent){
            stu[key] = editStudent[key]
        }

        writeStudentList(json)
        callBack()
    })
}

exports.deleteById = function (delId, callBack) {
    readStudentList(function (json) {

        let delIndex = json.studentList.findIndex(item => item.id == delId)

        json.studentList.splice(delIndex, 1)

        writeStudentList(json)

        callBack()
    })
}

function readStudentList(callBack) {
    fs.readFile("./page/crud/db.json", "utf-8", function (error, data) {
        if (!error) {
            callBack(JSON.parse(data))
        } else {
            throw new Error("读取错误")
        }
    })
}

exports.readStudentList = readStudentList

function writeStudentList(json) {
    fs.writeFile("./page/crud/db.json", JSON.stringify(json), function (error) {
        if (error) {
            throw new Error("写入错误")
        }
    })
}

exports.writeStudentList = writeStudentList